import { useSelector, useDispatch } from 'react-redux'
import { todoCheckAll } from '../../store/actions/todo'
import TodoItem from '../TodoItem'

export default function TodoMain() {
  const dispatch = useDispatch()
  const filter = useSelector((state) => state.filter)
  const list = useSelector((state) => {
    if (filter === 'active') {
      // 保留激活的
      return state.todo.filter((item) => !item.done)
    } else if (filter === 'completed') {
      // 保留完成的
      return state.todo.filter((item) => item.done)
    }
    // 保留所有
    return state.todo
  })
  // 由于点击全选，要在当前状态的基础上进行取反，所以呀，要先拿到当前状态
  const nowStatus = list.every((item) => item.done)
  const handleCheckAllChange = () => dispatch(todoCheckAll(!nowStatus))
  return (
    <section className='main'>
      <input
        id='toggle-all'
        className='toggle-all'
        type='checkbox'
        checked={nowStatus}
        onChange={handleCheckAllChange}
      />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {list.map((item) => (
          <TodoItem key={item.id} item={item} />
        ))}
      </ul>
    </section>
  )
}
